<?php

/**
 * LISTER
 *
 * Params:
 * 		LIST_OBJ
 *	 		obj_part 		- obj part id | GET support
 *	 		obj_subpart		- obj subpart id | GET support
 * 			tmpl_name 		- name of tmplate in {plugin}/_tmpl dir
 * 			per_page 		- elements on page - default 10
 * 			show_pager 		- true | false - default TRUE
 * 			page 			- current pager page
 * 			check_fields 	- array('field'=>array('value', 'comparators')) - list of fields to check
 * 			show_published 	- show only published objs - default TRUE
 * 
 * 		LIST
 * 			table			- table
 * 			tmpl_header		- name of header tmplate in {plugin}/_tmpl dir
 * 			tmpl_name 		- name of tmplate in {plugin}/_tmpl dir
 *  		tmpl_footer		- name of footer tmplate in {plugin}/_tmpl dir
 *  		per_page 		- elements on page - default 10
 * 			show_pager 		- true | false - default TRUE
 * 			page 			- current pager page
 * 			check_fields 	- array('field'=>array('value', 'comparators')) - list of fields to check
 * 			sort_by			- sort field
 * 			join			- array(array('t1.f', 't2.f')) - list of fields to join
 *   
 */
class zdListerComponents extends sfComponents
{
	
	public function setSort(&$c, $order, $field) {
		if ($order == 'asc')
			$c->addAscendingOrderByColumn ( $field );
		else
			$c->addDescendingOrderByColumn ( $field );
	}
	
  public function executeListMat($request)
  {
  	

			
  	
  	 if(isset($this->seo_title))
  	 {
  	 	$seo_title = $this->seo_title;
  	 }
  	 else {
  	 	$seo_title = '';
  	 }
    	 if(isset($this->seo_keyword))
  	 {
  	 	$seo_keyword = $this->seo_keyword;
  	 }
    	 else {
  	 	$seo_keyword = '';
  	 }
  	 
  	 
    	 if(isset($this->seo_description))
  	 {
  	 	$seo_description = $this->seo_description;
  	 }
    	 else {
  	 	$seo_description = '';
  	 }
  	 if($seo_title!='' and $seo_keyword!='' and $seo_description!='')
  	 {
  	   ////Устанавливаем заголовки
		  	$this->getResponse()->addMeta('title', $seo_title);
		    $this->getResponse()->addMeta('keywords', $seo_keyword);
		    $this->getResponse()->addMeta('description', $seo_description);
	   ////   
  	 }
  	 
		 
  	
        $c = new Criteria();
        $c->addJoin(MaterialPeer::TYPE_ID,TypeMaterialPeer::ID);
    
        //// Разборки с опубликованными
        
        if((!$this->getUser()->hasCredential('type_1') and !$this->getUser()->hasCredential('type_6') and !$this->getUser()->hasCredential('type_14')) and !$this->getVar('user_id'))
        {
        $c->add(MaterialPeer::PUB,1);
        }

        if(sfContext::getInstance()->getRequest()->getParameter('is_pub')=='true')
        {
        	$c->add(MaterialPeer::PUB,1);
        }
          if(sfContext::getInstance()->getRequest()->getParameter('is_pub')=='false')
        {
        	$c->add(MaterialPeer::PUB,0);
        }
        
        //// город 
        if(sfConfig::get('app_use_region_simple')==true)
        {
        	if(sfContext::getInstance()->getUser()->getAttribute('city_id')!=1)
        	{
				$crit1=$c->getNewCriterion(MaterialPeer::REGION_ID,sfContext::getInstance()->getUser()->getAttribute('city_id'));
				$crit2=$c->getNewCriterion(MaterialPeer::REGION_ID,1);
				$crit1->addOr($crit2);  
        		$c->add($crit1); 
        	}
        }
                  
        ////Тип материала
       if($this->getVar('mat_type')>0)
        {
	        $c->addAnd(MaterialPeer::TYPE_ID, $this->getVar('mat_type'));         
        }
        
          ////Материалы пользователя
       if($this->getVar('user_id')>0 and !$this->getUser()->hasCredential('type_1'))
        {
	        $c->addAnd(MaterialPeer::USER_ID, $this->getVar('user_id'));         
        }

        
          ////Новости по пользователю
       if($this->getVar('is_user')==true)
        {
	        $c->addJoin(MaterialPeer::USER_ID,FavoritePeer::FAV_ID);
	        $c->add(FavoritePeer::USER_ID,$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' )) ;   
        }
        
        
        ////На утверждении
       if($this->getVar('in_approve')==true)
        {
        	$c->add(MaterialPeer::CUSTOM_INT1,1);
        }
        

        
        
        ////Каталог
        if($this->folder_id>0 and $this->folder_id<>sfConfig::get ( 'app_folder_org' ) )
        {
            $c->addJoin(MaterialPeer::ID, Mat2FolderPeer::MATERIAL_ID);
	        $c->addAnd(Mat2FolderPeer::FOLDER_ID, $this->getVar('folder_id'));
	        $this->folder_name=FolderPeer::retrieveByPK($this->getVar('folder_id'));         
        }
        
      ////Буква
        if($this->getRequestParameter ( 'letter'))
        {
        	
           $c->addAnd(MaterialPeer::TITLE,$this->getRequestParameter ( 'letter').'%',Criteria::LIKE); 
        }
        
        //// Поиск 
        
         if(isset($this->search_key) and $this->search_key!='')
        { 
             $arr_key = explode(' ',$this->search_key);
            // $crit1=$c->getNewCriterion(MaterialPeer::ID, 'ee');
             
        	 if($this->search == 'in_enterprise')
        	 {
        	 	
        	 	        	   foreach($arr_key as $v)
				        	   {
				        	   	 //$crit2=$c->getNewCriterion(MaterialPeer::TITLE, '%'.$v.'%', Criteria::LIKE);
				        	   	// $crit1->addAnd($crit2);
				        	   	$c->addAnd(MaterialPeer::TITLE, '%'.$v.'%', Criteria::LIKE);
				        	   }
				        	  // $c->add($crit1);
        	   
        	 }
        	 elseif($this->search == 'in_news')
        	 {
        	 	$critb=$c->getNewCriterion(MaterialPeer::TYPE_ID,6); 	
                $critt=$c->getNewCriterion(MaterialPeer::TYPE_ID,6);   
                	        	 	foreach($arr_key as $v)
					        	   {
					        	   	 $critb1=$c->getNewCriterion(MaterialPeer::CONTENT, '%'.$v.'%', Criteria::LIKE);
					        	   	 $critb->addAnd($critb1);
					        	   	 
					                 $critt1=$c->getNewCriterion(MaterialPeer::TITLE, '%'.$v.'%', Criteria::LIKE);
					        	   	 $critt->addAnd($critt1);
					        	   	 
					        	   	 
					        	   }
					        	   
					        	   $critb->addOr($critt);
					        	   $c->add($critb);
        	 }
        	 else 
        	 {
        	   $c->addJoin(MaterialPeer::ID, Mat2FolderPeer::MATERIAL_ID);
               //$c->addAnd(Mat2FolderPeer::MATERIAL_ID, 'MATCH(mat2folder.TAG) AGAINST ("'.$this->search_key.'" IN BOOLEAN MODE)', Criteria::CUSTOM);
               
        	   
        	   foreach($arr_key as $v)
        	   {
        	   	 //$crit2=$c->getNewCriterion(Mat2FolderPeer::TAG, '%'.$v.'%', Criteria::LIKE);
        	   	 //$crit1->addOr($crit2);
        	   	// $c->addAnd(MaterialPeer::ID, 'MATCH(material.FOLDERS_ARRAY) AGAINST ("'.$v.'" IN BOOLEAN MODE)', Criteria::CUSTOM);
        	   	
        	   	 $c->addAnd(Mat2FolderPeer::TAG, '%'.$v.'%', Criteria::LIKE);
        	   }
        	  // $c->add($crit1);
        	   
        	   //$c->addAnd(Mat2FolderPeer::TAG, '%'.$this->search_key.'%', Criteria::LIKE);
               $c->addGroupByColumn(Mat2FolderPeer::MATERIAL_ID);	 
        	 }

        	 ////Устанавливаем класс пейджера
        	 $strpager  = 'GroupPager';
        	 
        }
        else 
        {

        	  ////Устанавливаем класс пейджера
        	  $strpager  = 'sfPropelPager';
        	  
        	  
               ////Украина или зарубеж
		       if($this->getVar('location')==true)
		        {
			        
		            if($_SESSION['region']=='zarubezh')
				    {
				    	 $c->add(MaterialPeer::CUSTOM_INT2,2);
				    }
				    else 
				    {
		               $c->add(MaterialPeer::CUSTOM_INT2,1);
				    }
		        	
		        }
        	
        }

        
          //// Добавление массива каталогов 
        
         if(isset($this->add_folder) and is_array($this->add_folder) )
        { 
        	//$c->addJoin(MaterialPeer::ID, Mat2FolderPeer::MATERIAL_ID);
        	$cr2=$c->getNewCriterion(MaterialPeer::PUB, 33);
        	$str='';
        	foreach($this->add_folder as $f )
        	{
        	  $str .= ' '.$f;
        	  $crit1=$c->getNewCriterion(Mat2FolderPeer::FOLDER_ID, $f);
        	  $cr2->addOr($crit1);	
        	}
        	
			   
			     $c->addAnd(MaterialPeer::ID, 'MATCH(material.FOLDERS_ARRAY) AGAINST ("'.$str.'" IN BOOLEAN MODE)', Criteria::CUSTOM);	        
        }
        
     
      /*
		 * проверяем на период отображения материала (НАЧАЛО)
		 */

        if(isset($this->use_period) and !$this->getVar('date_from') and !$this->getVar('archive') and  !$this->getVar('date_from_event') and !$this->getVar('all') )
        {
		$what_is_date=date('Y-m-d');
		$crit1=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE1, $what_is_date, Criteria::LESS_EQUAL);
		$crit2=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE2, $what_is_date, Criteria::GREATER_EQUAL);
		$crit1->addAnd($crit2);  
		$crit3=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE1, NULL, Criteria::ISNULL);
		$crit1->addOr($crit3);  
		$c->add($crit1);
        }

		/*
		 * проверяем на период отображения материала (КОНЕЦ)
		 */		
        
        
        /*
         * Фильтр по дате создания материала
         */
        
        if($this->getVar('date_from'))
        {
        $crit1=$c->getNewCriterion(MaterialPeer::CREATED_AT, $this->getVar('date_to'), Criteria::LESS_EQUAL);
		   	$crit2=$c->getNewCriterion(MaterialPeer::CREATED_AT, $this->getVar('date_from'), Criteria::GREATER_EQUAL);
		   	$crit1->addAnd($crit2); 
		   	$c->add($crit1);
			
        }
        
          /*
         * Фильтр по дате проведения выставок
         */
        
        if($this->getVar('date_from_event'))
        {

                $crit1=$c->getNewCriterion(MaterialPeer::CUSTOM_TIMESTAMP1, $this->getVar('date_to_event'), Criteria::GREATER_EQUAL);
			    $crit2=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE3, $this->getVar('date_from_event'), Criteria::GREATER_EQUAL);
			    $crit3=$c->getNewCriterion(MaterialPeer::CUSTOM_TIMESTAMP1, $this->getVar('date_from_event'), Criteria::GREATER_EQUAL);
			    $crit4=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE3, $this->getVar('date_to_event'), Criteria::LESS_EQUAL);
			    $crit1->addAnd($crit2); 
			    $crit1->addAnd($crit3);
			    $crit1->addAnd($crit4);
			    
			    
			    
			    $crit11=$c->getNewCriterion(MaterialPeer::CUSTOM_TIMESTAMP1, $this->getVar('date_to_event'), Criteria::GREATER_EQUAL);
			    $crit22=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE3, $this->getVar('date_from_event'), Criteria::LESS_EQUAL);
			    $crit11->addAnd($crit22); 
			    
			    
			    $crit222=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE3, $this->getVar('date_from_event'), Criteria::LESS_EQUAL);
			    $crit111=$c->getNewCriterion(MaterialPeer::CUSTOM_TIMESTAMP1, $this->getVar('date_to_event'), Criteria::LESS_EQUAL);
			    $crit333=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE3, $this->getVar('date_to_event'), Criteria::LESS_EQUAL); 
			    $crit444=$c->getNewCriterion(MaterialPeer::CUSTOM_TIMESTAMP1, $this->getVar('date_from_event'), Criteria::GREATER_EQUAL);
			    $crit111->addAnd($crit333); 
			    $crit111->addAnd($crit222);
			    $crit111->addAnd($crit444);
			    
			    $crit1111=$c->getNewCriterion(MaterialPeer::CUSTOM_TIMESTAMP1, $this->getVar('date_to_event'), Criteria::LESS_EQUAL);
			    $crit2222=$c->getNewCriterion(MaterialPeer::CUSTOM_DATE3, $this->getVar('date_from_event'), Criteria::GREATER_EQUAL);
			    $crit1111->addAnd($crit2222); 
			    
			    $c->add($crit1);
			    $c->addOr($crit11);
			    $c->addOr($crit111);
			    $c->addOr($crit1111);
			 
			    
        }        
        
        
          /*
         * Фильтр по архиву
         */
        
        if($this->getVar('archive'))
        {
        	$c->add(MaterialPeer::CUSTOM_DATE2, date('Y-m-d'), Criteria::LESS_THAN);
			
        }
        
        
    
    
        //// Сортировка
        if(isset($this->sort_rating))
        {
        		$c->addDescendingOrderByColumn(MaterialPeer::RATING);
        		$c->addDescendingOrderByColumn(MaterialPeer::ID);
        }
         elseif(isset($this->sort_date))
        {
        		$c->addDescendingOrderByColumn(MaterialPeer::ID);
        }
         elseif(isset($this->sort_abc))
        {
        	    $c->addDescendingOrderByColumn(MaterialPeer::RATING);
        		$c->addAscendingOrderByColumn(MaterialPeer::TITLE);
        }
        else 
        {
        	    $orders = array ('asc' => 'desc', 'desc' => 'asc' );
		if (! isset ( $this->sort ))
		        ////Устанавливаем дефолт
			    if(isset($this->mat_type) and $this->mat_type==14){
			      $this->sort = $this->getRequestParameter ( 'sort', 6 );
			    }
			    else{
				  $this->sort = $this->getRequestParameter ( 'sort', 5 );
			    }
			    
		if (! isset ( $this->order ))
			$this->order = $this->getRequestParameter ( 'order', 'desc' );
			
  		switch ($this->sort) {
			case 1 :
				$this->setSort ( $c, $this->order, MaterialPeer::RATING );
				break; // рейтинг
			case 2 :
				$this->setSort ( $c, $this->order, MaterialPeer::SEE );
				break; // оценка
			case 3 :
				$this->setSort ( $c, $this->order, MaterialPeer::UPDATED_AT );
				break;
			case 4 :
				///Алфавит
				$this->setSort ( $c, $this->order, MaterialPeer::TITLE );
				break;
			case 5 :
				///Дефолт
				$c->addDescendingOrderByColumn(MaterialPeer::CUSTOM_INT3);		
				$c->addDescendingOrderByColumn(MaterialPeer::RATING);
				$c->addDescendingOrderByColumn(MaterialPeer::UPDATED_AT);
				break;				
			case 6 :
				///Дата начала мероприятия
				$c->addAscendingOrderByColumn(MaterialPeer::CUSTOM_DATE3);	
				break;				
			 default :
			    $c->addAscendingOrderByColumn(MaterialPeer::CUSTOM_INT3);
        		$c->addAscendingOrderByColumn(MaterialPeer::TITLE);
				break;

		     }	
        }
    
        ///
        
        
    	$this->per_page = $this->getVar('per_page', 10);
        if (!isset($this->page))
        	$this->page = $this->getRequestParameter('page', 1);

        $pager = new $strpager('Material', $this->per_page);
        $pager->setCriteria($c);
        $pager->setPeerMethod('doSelect');        
        $pager->setPage($this->page);
        $pager->init();
        $this->pager = $pager;
        
        ////Записываем в лог показы 
        if(isset($this->search_key) and $this->getVar('mat_type')==1)
        {
        	foreach($pager->getResults() as $v)
        	{
          	$l = new Searchlog();
          	$l->setMatId($v->getId());
          	$l->setKey($this->search_key);
          	$l->setLevel(5);
          	$l->save();
        	}
        }
        ///
  }


  public function executeList($request)
  {
    $c = new Criteria();

	// join
	    if(is_array($this->getVar('join', '')))
	    {
	        foreach ($this->join as $v)
	        {
				$c->addJoin($v[0], $v[1]);
	        }
	    }
	    
    // check fields
	    if(is_array($this->getVar('check_fields', '')))
	    {
	        foreach ($this->check_fields as $k=>$v)
	        {
	            $c->add($k, $v[0], $v[1]);
	        }
	    }
	    
	// order
		if ($this->getVar('sort_by', '') != '')
			$c->addAscendingOrderByColumn($this->sort_by);
	    
	// pager
    	$this->per_page = $this->getVar('per_page', 10);
        if (!isset($this->page))
        	$this->page = $this->getRequestParameter('page', 1);

    // do select
        $pager = new sfPropelPager($this->table, $this->per_page);
        $pager->setCriteria($c);
        $pager->setPage($this->page);
        $pager->setPeerMethod('doSelect');
        $pager->init();
        $this->pager = $pager;
  }
  
  
public function  executeShowabc()
  {
  	
  }
  
}
?>